const user = {
    state: () => {
        // 检查 localStoreage 中是否存在 user 信息
        const userJsonStr = window.localStorage.getItem("user");

        // 如果有，就使用 localStorage 中的用户信息，来初始化仓库中的 state
        if (userJsonStr) {
            return JSON.parse(userJsonStr);
        }

        // 如果没有，就返回初始化的 state
        return {
            token: "",
            username: "",
            nickname: "",
        };
    },
    mutations: {
        /**
         * 登录成功后，修改 state 值
         * @param {*} state
         * @param {*} payload
         */
        loginSuccess(state, payload) {
            state.token = payload.token;
            state.username = payload.user.username;
            state.nickname = payload.user.nickname;
        },
        /**
         * 退出登录
         * @param {*} state
         */
        logout(state) {
            state.token = "";
            state.username = "";
            state.nickname = "";
        },
    },
};

export default user;
